import { mapField, useFormValue } from '@/components';
import { commonRules, enumToOptions, getAccept } from '@/utils';
import moment from 'moment';
import { useEffect } from 'react';
import CompanyInfoEditor from './CompanyInfoEditor';

const titleMap = {
  SF: '投保流程',
  PP: '保全流程',
  CF: '理赔流程',
  QP: '职业类别表',
};
const codes = Object.keys(titleMap);

export const formToData = (formData, originalData) => {
  const { annual, ...data } = formData;

  data.foundedTime = data.foundedTime?.format('YYYY-MM-DD');

  data.productAttachments = [];
  const addInfo = (item, showType) => {
    let list = [].concat(item);

    list.forEach((listItem) => {
      data.productAttachments.push({
        id: listItem.id,
        attachmentUrl: listItem.url,
        attachmentType: listItem.ext,
        richTextInfo: listItem.name,

        contentType: '2',
        showContentTitle: titleMap[showType],
        showContentType: showType,
        companyCode: data.code,
        status: listItem.url ? 1 : 0,
      });
    });
  };

  codes.forEach((code) => {
    data[code]?.forEach((item) => {
      addInfo(item, code);
    });
    delete data[code];
  });

  return data;
};

export const dataToForm = (data) => {
  if (!data) return null;
  const { productAttachments, ...formData } = data;

  formData.foundedTime = formData.foundedTime && moment(formData.foundedTime);

  productAttachments?.forEach((info) => {
    const { id, showContentType: showType, attachmentUrl: url, attachmentType: ext, richTextInfo: name } = info;
    const item = { id, url, ext, name };
    formData[showType] = (formData[showType] || []).concat([item]);
  });

  return formData;
};

const eto = enumToOptions;

export const natureTypes = [
  '股份有限公司',
  '有限责任公司',
  '平台型寿险公司',
  '股份有限公司（中外合资）',
  '有限责任公司（台港澳与境内合资）',
  '有限责任公司（中外合资）',
  '有限责任公司(中外合资)',
  '有限责任公司(中外合资)',
  '有限责任公司(中外合资)',
  '其他股份有限公司(非上市)',
  '有限责任公司(中外合资）',
  '其他股份有限公司(非上市)',
  '股份有限公司(非上市)',
  '外商投资企业投资',
  '股份制',
  '其他股份有限公司(非上市)',
  '合资寿险公司',
  '其他股份有限公司(非上市)',
  '合资保险公司',
  '国内首家相互人寿保险组织',
].map((v) => ({ value: v, label: v }));

const today = new Date();
const formatDate = (props) => ({
  ...props,
  getValueFromEvent(value) {
    return value.format('YYYY-MM-DD');
  },
  getValueProps(value) {
    return { value: value ? moment(value) : null };
  },
});

export const fields = {
  base: [
    ['code', '公司code', null, { required: true, rules: commonRules.code2 }],
    ['serviceCode', 'service代理公司code', null, { required: true, rules: commonRules.code2 }],
    ['nameChn', '公司中文名称', null, { required: true }],
    ['nameEn', '公司英文名称', null, {}],
    ['nameAbbr', '公司名称缩写', null, {}],
    [
      'createDate',
      '公司成立时间',
      'date',
      formatDate({
        disabledDate(date) {
          return today < date._d;
        },
        showToday: false,
      }),
    ],
    ['comNature', '公司性质', 'select', { options: natureTypes }],
    ['address', '公司地址', null, {}],
    ['customerTellphone', '公司客服电话', null, {}],
    ['fax', '公司传真', null, {}],
    ['website', '公司官网地址', null, {}],
    ['registeredCapital', '公司注册资本', null, {}],
    ['peoControl', '公司实际控制人', null, {}],
    ['cliaimMoney', '理赔总额', null, {}],
    ['cliaimTime', '理赔时效', null, {}],
    [['companyClaimSettlementAddressList', 0, 'claimSettlementAddress'], '理赔地址', null, {}],
    ['sarmra', '公司SARMRA评分', null, {}],
    ['isInside', '是否主要推荐', 'radio-group', { initialValue: '0', options: eto({ 0: '不主推', 1: '主推' }) }],
    [
      'supportPlan',
      '是否支持计划书',
      'radio-group',
      { initialValue: '0', options: eto({ 0: '支持计划书', 1: '不支持计划书' }) },
    ],
    [
      'supportInsurance',
      '是否支持投保',
      'radio-group',
      { initialValue: '0', options: eto({ 0: '支持投保', 1: '不支持投保' }) },
    ],
    [
      'createProposalFlag',
      '生成建议书标志',
      'radio-group',
      { required: true, initialValue: '', options: eto({ 0: '否', 1: '是' }) },
    ],
    [
      'createPrompFlag',
      '是否生成投保提示书',
      'radio-group',
      { initialValue: '0', options: eto({ 0: '不生成', 1: '生成' }) },
    ],
    ['effectDate', '生效时间', 'date', formatDate({ required: true })],
    ['expiryDate', '失效时间', 'date', formatDate({ required: true })],
    ['shareholder', '公司股东情况', null, {}],
    [
      'companyIntro',
      '公司简介',
      CompanyInfoEditor,
      {
        placeholder: '请输入公司简介',
        maxLength: 1000,
        colProps: { xs: 24, md: 24, xl: 20 },
        itemProps: {
          labelCol: { xs: 8, md: 4, xl: 3 },
          wrapperCol: { xs: 16, md: 24 },
        },
      },
    ],
  ].map(mapField),

  // 携赔
  xp: [
    ['claimDisplay', '是否支持携赔', 'radio-group', { initialValue: '0', options: eto({ 0: '显示', 1: '不显示' }) }],
    [
      'selfServiceClaimSettlementFlag',
      '在线理赔标识',
      'radio-group',
      { initialValue: '0', options: eto({ 0: '是', 1: '否' }) },
    ],
    ['cooperationFlag', '合作标识', 'radio-group', { initialValue: '0', options: eto({ 0: '是', 1: '否' }) }],
    ['materialId', '资料库id', null, {}],
    ['reportTelephone', '报案电话', null, {}],
    ['claimSettlementAddressId', '理赔申请地址id', null, {}],
  ].map(mapField),

  // 点滴保
  dd: [
    ['supportDiandibao', '是否支持点滴保', 'radio-group', { initialValue: '0', options: eto({ 0: '是', 1: '否' }) }],
    [
      'dianDiCode',
      '点滴保公司code',
      null,
      {
        getFieldProps(e, index, form) {
          const value = useFormValue(form, 'supportDiandibao');

          const disabled = `${value}` === '1';
          useEffect(() => {
            if (`${value}` === '1') {
              form.setFieldsValue({ [e.name]: '' });
            }
          }, [value]);

          return { disabled };
        },
      },
    ],
  ].map(mapField),

  service: [
    // SF 投保流程，SP保全流程，CF理赔流程,
    [['SF', 0, 'url'], '投保流程', 'named-upload'],
    [['PP', 0, 'url'], '保全流程', 'named-upload'],
    [['CF', 0, 'url'], '理赔流程', 'named-upload'],
  ].map(mapField, {
    merge: { required: true, accept: getAccept('doc', 'image', 'excel'), fileNameProp: 'name', fileTypeProp: 'ext' },
  }),

  attachment: [
    // QP 职业类别
    [['QP', 0, 'url'], '职业类别', 'named-upload'],
  ].map(mapField, {
    merge: { accept: getAccept('doc'), fileNameProp: 'name', fileTypeProp: 'ext' },
  }),
};

const pad = (str, len) => str.substr(0, len).padStart(len, '1'.padEnd(len, '0'));
export const numId = () => pad(`${Math.random() * Date.now()}`.replace(/^0|\./g, ''), 21);
